<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class FinanceEnergyCoin extends Base
{
    protected $table = 'finance_energy_coin_stream';

    private $redis_cache_finance_user_wallet = "CACHE:FINANCE:USER:WALLET";

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }


    /**
     * 更新用户能量币
     * @param int $userId 更新该user_id
     * @param int $dataId 数据ID
     * @param int $energyCoinType 类型 1=愤怒的小鸟奖励 
     *                  101=商店兑换扣除
     * @param int $changeValue 变动值 支出使用负数
     * @param string $changeDesc 变动描述
     * @param int $dataType 数据类型 1=局数ID 2=礼物ID
     * @return bool
     */
    public function inc($userId, $dataId, $energyCoinType, $changeValue, $changeDesc, $value1=0){
        if(empty($userId)) {
            return false;
        }
        $dataType = 0;
        if(in_array($energyCoinType, [1])) {
            $dataType = 1;
        }elseif(in_array($energyCoinType, [101])) {
            $dataType = 2;
        }

        if(in_array($energyCoinType, [1, 2])) {
            $changeValue = abs($changeValue);
        }else{
            $changeValue = 0 - abs($changeValue);
        }

        DB::table("finance_wallet")
            ->where('user_id', '=', $userId)
            ->increment('energy_coin', $changeValue, ['change_timestamp'=> time()]);

        DB::table($this->table)->insert([
            "user_id" => $userId,
            "change_value" => $changeValue,
            "change_desc" => $changeDesc,
            "energy_coin_type" => $energyCoinType,
            "data_id" => $dataId,
            "data_type" => $dataType,
            "value1" => $value1,
            "change_timestamp" => time()
        ]);

        Redis::DEL($this->redis_cache_finance_user_wallet . ':' . $userId);
        return true;
    }

    /**
     * 能量能量币记录列表
     */
    public function energyCoinList($page, $limit, $where){
        $query = DB::table($this->table);
        if(!empty($where['user_id'])) {
            $query = $query->where('user_id', $where['user_id']);
        }
        if(!empty($where['energy_coin_type'])) {
            $query = $query->where('energy_coin_type', $where['energy_coin_type']);
        }
        $query = $query->orderBy('stream_id', 'desc')
            ->offset($page * $limit)->limit($limit);
        $list = $query->get();
        $list = objToArray($list);

        return $list;
    }


}
